package com.gack.business.service;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gack.business.dao.DepartmentDao;
import com.gack.business.dao.EnterpriseDao;
import com.gack.business.dao.UserDao;
import com.gack.business.dao.UserEnterpriseDepartmentPositionDao;
import com.gack.business.model.Contacts;
import com.gack.business.model.DepositRecord;
import com.gack.business.model.Message;
import com.gack.business.model.Permission;
import com.gack.business.model.User;
import com.gack.business.model.UserEnterpriseDepartmentPosition;
import com.gack.business.model.UserEnterprisePermissionGroup;
import com.gack.business.repository.ContactsRepository;
import com.gack.business.repository.DepartmentRepository;
import com.gack.business.repository.DepositRecordRepository;
import com.gack.business.repository.EnterpriseRepository;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.PermissionRepository;
import com.gack.business.repository.PositionRepository;
import com.gack.business.repository.UserEnterpriseDepartmentPositionRepository;
import com.gack.business.repository.UserEnterprisePermissionGroupRepository;
import com.gack.business.repository.UserRepository;
import com.gack.business.vo.ContactsDetailVO;
import com.gack.business.vo.EnterpriseItemVO;
import com.gack.business.vo.TopDepartmentAndUserItemVO;
import com.gack.business.vo.UserDetailVO;
import com.gack.business.vo.UserItemVO;
import com.gack.helper.common.config.PayConfig;
import com.gack.helper.common.util.HttpGetUtil;
import com.gack.helper.common.util.MapAsReturn;
import com.gack.helper.common.util.Pinyin;


/**
 * 
 * @author ws 2018-5-30
 */
@Service
@Transactional
public class UserService implements UserServiceInterface {

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private EnterpriseRepository enterpriseRepository;
	@Autowired
	private EnterpriseDao enterpriseDao;
	@Autowired
	private DepartmentRepository departmentRepository;
	@Autowired
	private ContactsRepository contactsRepository;
	@Autowired
	private DepositRecordRepository depositRecordRepository;
	@Autowired
	private UserEnterpriseDepartmentPositionRepository userEnterpriseDepartmentPositionRepository;
	@Autowired
	private PositionRepository positionRepository;
	@Autowired
	private DepartmentServiceInterface departmentService;
	@Autowired
	private DepartmentDao departmentDao;
	@Autowired
	private UserEnterpriseDepartmentPositionDao userEnterpriseDepartmentPositionDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private MessageRepository messageRepository;
	@Autowired
	private UserEnterprisePermissionGroupRepository userEnterprisePermissionGroupRepository;
	@Autowired
	private PermissionRepository permissionRepository;

	/**
	 * 根据查询名称,查找当前公司的用户(输入的查询名称应匹配用户应显示的名称(好友备注名或企业备注名))
	 * 根据查询手机号,查找当前公司用户(模糊查询)
	 * @param userId 操作者id
	 * @param enterpriseId 公司id
	 * @param input 用户输入的查询名称或查询手机号
	 * @return  status:error/success  msg:错误或成功消息   userItemList:匹配到的用户VO集合
	 */
	public Map<String, Object> findUserItemVOByInput(String userId, String enterpriseId, String input){
		Set<UserItemVO> set = new TreeSet<>(new Comparator<UserItemVO>(){
			@Override
			public int compare(UserItemVO o1, UserItemVO o2) {
				String s1 = o1.getId();
				String s2 = o2.getId();
				return s1.compareTo(s2);
			}
		});
		if(Pattern.matches("[0-9]*", input)){
			Map<String, Object> map1 = findUserItemVOByInputName(userId, enterpriseId, input);
			Map<String, Object> map2 = findUserItemVOByInputTel(userId, enterpriseId, input);
			if(map1.get("status").equals("error") || map2.get("status").equals("error")){
				return MapAsReturn.setStatusError("查询用户异常");
			}
			set.addAll((List<UserItemVO>)map1.get("userItemList"));
			set.addAll((List<UserItemVO>)map2.get("userItemList"));
		}else{
			Map<String, Object> map1 = findUserItemVOByInputName(userId, enterpriseId, input);
			if(map1.get("status").equals("error")){
				return MapAsReturn.setStatusError("查询用户异常");
			}
			set.addAll((List<UserItemVO>)map1.get("userItemList"));
		}
		
		// 对userVOList排序,按nameForShow排序
		List<UserItemVO> userItemVOList = new ArrayList<>(set);
		Comparator<UserItemVO> comparator = new Comparator<UserItemVO>() {
			@Override
			public int compare(UserItemVO u1, UserItemVO u2) {
				String s1 = Pinyin.getStringPinYin(u1.getNameForShow());
				String s2 = Pinyin.getStringPinYin(u2.getNameForShow());

				return s1.compareTo(s2);
			}
		};
		Collections.sort(userItemVOList, comparator);
		
		return MapAsReturn.setStatusSuccess("userItemList", userItemVOList);
	}
	
	/**
	 * 根据查询名称,查找当前公司的用户
	 * 			规则为:输入的查询名称应匹配用户应显示的名称(好友备注名或企业备注名)
	 * @param userId 操作者id
	 * @param enterpriseId 公司id
	 * @param inputName 用户输入的查询名称
	 * @return  status:error/success  msg:错误或成功消息   userItemList:匹配到的用户VO
	 */
	@Override
	public Map<String, Object> findUserItemVOByInputName(String userId, String enterpriseId, String inputName) {
		//获取符合条件的UserItemVO对象集合
		List<UserItemVO> userItemVOListTemp = userDao.findUserItemVOByInputName(userId, enterpriseId, inputName);
		
		//建立游离状态的userItemVO对象集合
		List<UserItemVO> userItemVOList = new ArrayList<>();
		for(UserItemVO t : userItemVOListTemp){
			UserItemVO temp = new UserItemVO();
			temp.setId(t.getId());
			temp.setUsername(t.getUsername());
			temp.setPortrait(t.getPortrait());
			temp.setNameForShow(t.getNameForShow());
			temp.setRoleId(t.getRoleId());
			userItemVOList.add(temp);
		}
		
		//添加roleId
		List<UserEnterprisePermissionGroup> uepgList = userEnterprisePermissionGroupRepository.findManager(enterpriseId);
		for(UserItemVO t : userItemVOList){
			t.setRoleId("3");
			for(UserEnterprisePermissionGroup element : uepgList){
				if(element.getUserId().equals(t.getId())){
					if(element.getOpenDescription().contains("SUPER_PERMISSION")){
						t.setRoleId("1");
					}else{
						t.setRoleId("2");
					}
				}
			}
		}

		// 对userVOList排序,按nameForShow排序
		Comparator<UserItemVO> comparator = new Comparator<UserItemVO>() {
			@Override
			public int compare(UserItemVO u1, UserItemVO u2) {
				String s1 = Pinyin.getStringPinYin(u1.getNameForShow());
				String s2 = Pinyin.getStringPinYin(u2.getNameForShow());

				return s1.compareTo(s2);
			}
		};
		Collections.sort(userItemVOList, comparator);

		return MapAsReturn.setStatusSuccess("userItemList", userItemVOList);
	}

	/**
	 * 根据查询手机号,查找当前公司用户(模糊查询)
	 * @param userId 操作者id
	 * @param enterpriseId 公司id
	 * @param inputTel 用户输入的手机号
	 * @return  status:error/success  msg:错误或成功消息   userItemList:匹配到的用户VO集合
	 */
	public Map<String, Object> findUserItemVOByInputTel(String userId, String enterpriseId, String inputTel){
		//获取符合条件的UserItemVO对象集合
		List<UserItemVO> userItemVOListTemp = userDao.findUserItemVOByInputTel(userId, enterpriseId, inputTel);
		
		//建立游离状态的userItemVO对象集合
		List<UserItemVO> userItemVOList = new ArrayList<>();
		for(UserItemVO t : userItemVOListTemp){
			UserItemVO temp = new UserItemVO();
			temp.setId(t.getId());
			temp.setUsername(t.getUsername());
			temp.setPortrait(t.getPortrait());
			temp.setNameForShow(t.getNameForShow());
			temp.setRoleId(t.getRoleId());
			userItemVOList.add(temp);
		}
		
		//添加roleId
		List<UserEnterprisePermissionGroup> uepgList = userEnterprisePermissionGroupRepository.findManager(enterpriseId);
		for(UserItemVO t : userItemVOList){
			t.setRoleId("3");
			for(UserEnterprisePermissionGroup element : uepgList){
				if(element.getUserId().equals(t.getId())){
					if(element.getOpenDescription().contains("SUPER_PERMISSION")){
						t.setRoleId("1");
					}else{
						t.setRoleId("2");
					}
				}
			}
		}

		// 对userVOList排序,按nameForShow排序
		Comparator<UserItemVO> comparator = new Comparator<UserItemVO>() {
			@Override
			public int compare(UserItemVO u1, UserItemVO u2) {
				String s1 = Pinyin.getStringPinYin(u1.getNameForShow());
				String s2 = Pinyin.getStringPinYin(u2.getNameForShow());

				return s1.compareTo(s2);
			}
		};
		Collections.sort(userItemVOList, comparator);

		return MapAsReturn.setStatusSuccess("userItemList", userItemVOList);
	}
	
	/**
	 * 用户查询无部门的人员信息
	 * @param enterpriseId 企业id
	 * @param userId 操作者id
	 * @return status:error/success msg:错误后成功信息 userItemVOList:无部门用户VO集合
	 */
	@Override
	public Map<String, Object> findNoDepartmentUserItemVO(String enterpriseId, String userId) {
		Map<String, Object> map = new HashMap<>();

		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if (!hasEnterprise) {
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}

		boolean hasUser = userRepository.exists(userId);
		if (!hasUser) {
			map.put("status", "error");
			map.put("msg", "查无此用户");
			return map;
		}

		//获取符合条件的UserItemVO对象集合
		List<UserItemVO> userItemVOListTemp = userDao.findNoDepartmentUserItemVO(enterpriseId, userId);
		
		//建立游离状态的userItemVO对象集合
		List<UserItemVO> userItemVOList = new ArrayList<>();
		for(UserItemVO t : userItemVOListTemp){
			UserItemVO temp = new UserItemVO();
			temp.setId(t.getId());
			temp.setUsername(t.getUsername());
			temp.setPortrait(t.getPortrait());
			temp.setNameForShow(t.getNameForShow());
			temp.setRoleId(t.getRoleId());
			userItemVOList.add(temp);
		}

		//添加roleId
		List<UserEnterprisePermissionGroup> uepgList = userEnterprisePermissionGroupRepository.findManager(enterpriseId);
		for(UserItemVO t : userItemVOList){
			t.setRoleId("3");
			for(UserEnterprisePermissionGroup element : uepgList){
				if(element.getUserId().equals(t.getId())){
					if(element.getOpenDescription().contains("SUPER_PERMISSION")){
						t.setRoleId("1");
					}else{
						t.setRoleId("2");
					}
				}
			}
		}
		
		// 对userItemVOList排序,按nameForShow排序
		Comparator<UserItemVO> comparator = new Comparator<UserItemVO>() {
			@Override
			public int compare(UserItemVO u1, UserItemVO u2) {
				String s1 = Pinyin.getStringPinYin(u1.getNameForShow());
				String s2 = Pinyin.getStringPinYin(u2.getNameForShow());

				return s1.compareTo(s2);
			}
		};
		Collections.sort(userItemVOList, comparator);

		map.put("userItemVOList", userItemVOList);
		map.put("status", "success");
		map.put("msg", "操作成功");

		return map;
	}

	/**
	 * 
	 * <p>
	 * Title: payDeposit
	 * </p>
	 * <p>
	 * Description:用户支付押金接口
	 * </p>
	 * 
	 * @param userId
	 * @return
	 * @see com.gack.business.service.UserServiceInterface#payDeposit(java.lang.String)
	 */
	@Override
	public Map<String, String> payDeposit(String userId, String channel, String amount) {
		Map<String, String> map = new HashMap<>();
		User user = userRepository.findOne(userId);
		map.put("state", "FAIL");
		if (user.is_check()) {
			if (user.getIsPledge().intValue() == 0) {
				// 调用押金支付接口
				String baseUrl = PayConfig.PAY_URL;
				StringBuffer url = new StringBuffer();
				url.append(baseUrl).append("?uid=").append(user.getId()).append("&systemCode=").append("11")
						.append("&channel=").append(channel).append("&amount=").append(amount).append("&business_card_type=")
						.append("5").append("&originalId=").append("AABBCCDD");
				String result = HttpGetUtil.httpGet(url.toString());
				// System.out.println(result);
				JSONObject parseObject = JSON.parseObject(result);
				map = JSON.toJavaObject(parseObject, Map.class);
				System.out.println(map);
				if (map.get("status") != null && "SUCCESS".equals(map.get("status"))){
					map.put("state", "SUCCESS");
					return map;
				}
					
			} else {
				map.put("msg", "2");//用户已缴纳押金
			}
		} else {
			map.put("msg", "1");//用户未认证
		}
		return map;

	}



	@Override
	public User findUser(String id) {
		// TODO Auto-generated method stub
		return userRepository.findOne(id);
		
	}

	


	@Override
	public Map<String, String> refundDeposit(String userId) {
		Map<String, String> map = new HashMap<>();
		User user = userRepository.findOne(userId);
		map.put("state", "FAIL");
		if (user.getIsPledge().intValue() == 1) {
			// 调用押金支付接口
			String baseUrl = PayConfig.REFUND_URL;
			StringBuffer url = new StringBuffer();

			try {
				url.append(baseUrl).append("?id=").append(userId).append("&ask_name=").append(user.getUsername())
						.append("&ask_description=").append(URLEncoder.encode("退押金", "UTF-8")).append("&kind=")
						.append("11");
			} catch (Exception e) {
				e.printStackTrace();
			}
			String result = HttpGetUtil.httpGet(url.toString());
			// System.out.println(result);
			JSONObject parseObject = JSON.parseObject(result);
			map = JSON.toJavaObject(parseObject, Map.class);
			System.out.println(map);
			if (map.get("status") != null && "SUCCESS".equals(map.get("status"))){
				user.setIsPledge(2);
				userRepository.save(user);
				List<DepositRecord> records = depositRecordRepository.findByUidOrderByCreateTimeDesc(userId);
				DepositRecord record = records.get(0);
				DepositRecord newRecord = new DepositRecord(record);
				depositRecordRepository.save(newRecord);
				map.put("state", "SUCCESS");
				return map;
			}
		} else {
			map.put("msg", "用户未缴纳押金");
		}
		return map;
	}


	/**
	 * 查询某用户的角色等级
	 * @param userId 用户id
	 * @param enterpriseId 公司id
	 * @param departmentId 部门id
	 * @return  status:error/success  msg:错误或成功消息   level:角色等级
	 */
	@Override
	public Map<String, Object> findLevelByUserIdAndEnterpriseIdAndDepartmentId(String userId, String enterpriseId, String departmentId) {
		Map<String, Object> map = new HashMap<>();
		
		boolean hasUser = userRepository.exists(userId);
		if(!hasUser){
			map.put("status", "error");
			map.put("msg", "查无此用户");
			return map;
		}
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		boolean hasDepartment = departmentRepository.exists(departmentId);
		if(!hasDepartment){
			map.put("status", "error");
			map.put("msg", "查无此部门");
			return map;
		}
		
		String level = "3";
		List<UserEnterprisePermissionGroup> uepgList = userEnterprisePermissionGroupRepository.findManager(enterpriseId);
		for(UserEnterprisePermissionGroup element : uepgList){
			if(element.getOpenDescription().contains("SUPER_PERMISSION")){
				level = "1";
			}else{
				level = "2";
			}
		}
		
		map.put("level", level);
		map.put("status", "success");
		map.put("msg", "操作成功");
		
		return map;
	}
	
	/**
	 * 查询某用户所在的公司。公司按创建时间,降序排序
	 * @param userId 用户id
	 * @param enterpriseId 企业id
	 * @return  status:error/success  msg:错误或成功消息      enterpriseItemVOList:公司ItemVO集合
	 */
	@Override
	public Map<String, Object> findEnterpriseItemVOListByUserId(String userId, String enterpriseId){
		Map<String, Object> map = new HashMap<>();
		
		boolean hasUser = userRepository.exists(userId);
		if(!hasUser){
			map.put("status", "error");
			map.put("msg", "查无此用户");
			return map;
		}
		
		if(enterpriseId != null && enterpriseId.trim().length() != 0){
			boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
			if(!hasEnterprise){
				map.put("status", "error");
				map.put("msg", "查无此公司");
				return map;
			}
		}
		
		List<EnterpriseItemVO> enterpriseItemVOList = enterpriseRepository.findEnterpriseItemVOListByUserId(userId);
		
		//放置一级部门及其下所有人员信息
		if(enterpriseItemVOList.size() != 0){
			for(EnterpriseItemVO t : enterpriseItemVOList){
				Map<String, Object> tMap = departmentService.findTopDepartmentAndUserItemVO(t.getId(), userId);
				if(tMap.get("status").equals("success")){
					t.setTopDepartmentAndUserVOList((List<TopDepartmentAndUserItemVO>)tMap.get("topDepartmentAndUserVOList"));
				}
			}
		}
		
		
//		//将当前所在公司放在第一位
//		if(enterpriseId != null && enterpriseId.trim().length() != 0){
//			if(enterpriseItemVOList.size() != 0){
//				for(EnterpriseItemVO t : enterpriseItemVOList){
//					if(t.getId().equals(enterpriseId)){
//						enterpriseItemVOList.remove(t);
//						enterpriseItemVOList.add(0, t);
//						break;
//					}
//				}
//			}
//		}
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		map.put("enterpriseItemVOList", enterpriseItemVOList);
		return map;		
	}
	
	/**
	 * 查询某用户管理的公司(在该公司是管理员权限),并将当前公司放在第一位。其他公司按创建时间,降序排序
	 * @param userId 用户id
	 * @param enterpriseId 公司id 可为空
	 * @param inviteeId 被邀请者id 可为空
	 * @return  status:error/success  msg:错误或成功消息      enterpriseItemVOList:公司ItemVO集合
	 */
	@Override
	public Map<String, Object> findManageEnterpriseListByUserId(String userId, String enterpriseId, String inviteeId) {
		Map<String, Object> map = new HashMap<>();
		
		boolean hasUser = userRepository.exists(userId);
		if(!hasUser){
			map.put("status", "error");
			map.put("msg", "查无此用户");
			return map;
		}
		
		if(enterpriseId != null && enterpriseId.trim().length() != 0){
			boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
			if(!hasEnterprise){
				map.put("status", "error");
				map.put("msg", "查无此公司");
				return map;
			}
		}
		
		List<EnterpriseItemVO> enterpriseItemVOList = userEnterpriseDepartmentPositionRepository.findEnterpriseItemVOListByUserId(userId);
		
		if(enterpriseId != null && enterpriseId.trim().length() != 0){
			if(enterpriseItemVOList.size() != 0){//将当前所在公司放在第一位
				for(EnterpriseItemVO t : enterpriseItemVOList){
					if(t.getId().equals(enterpriseId)){
						enterpriseItemVOList.remove(t);
						enterpriseItemVOList.add(0, t);
						break;
					}
				}
			}
		}
		
		//判断被邀请者是否已在这些公司内
		if(inviteeId != null && inviteeId.trim().length() != 0){
			for(EnterpriseItemVO t : enterpriseItemVOList){
				if(userEnterpriseDepartmentPositionRepository.countByUserIdAndEnterpriseId(inviteeId, t.getId())>0){
					t.setHasIn(true);
				}else{
					t.setHasIn(false);
				}
			}
		}
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		map.put("enterpriseItemVOList", enterpriseItemVOList);
		return map;		
	}
	
	/**
	 * 为用户设置某个公司下的企业备注
	 * @param userId 用户id
	 * @param enterpriseId 公司id
	 * @param enterpriseRemarks 企业备注
	 * @return status:error/success  msg:错误或成功消息
	 */
	@Override
	public Map<String, Object> setEnterpriseRemarks(String userId, String enterpriseId, String enterpriseRemarks) {
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		//设置企业备注  无须防止重名
		List<UserEnterpriseDepartmentPosition> uedpList = userEnterpriseDepartmentPositionRepository.findByUserIdAndEnterpriseId(userId, enterpriseId);
		if(uedpList.size() == 0){
			map.put("status", "error");
			map.put("msg", "此用户不在此公司");
			return map;
		}else{
			UserEnterpriseDepartmentPosition uedp = uedpList.get(0);
			uedp.setEnterpriseRemarks(enterpriseRemarks);
			uedp.setUpdateTime(new Date());
			userEnterpriseDepartmentPositionRepository.save(uedp);
			
			map.put("status", "success");
			map.put("msg", "操作成功");
			return map;
		}
	}
	
	/**
	 * 为某个用户设置职位    更改或新增
	 * @param userId 用户id
	 * @param enterpriseId 公司id
	 * @param positionId 职位id
	 * @param operatorId 操作者id
	 * @return
	 */
	@Override
	public Map<String, Object> setPosition(String userId, String enterpriseId, String positionId, String operatorId) {
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		if(positionRepository.countByEnterpriseIdAndPositionId(enterpriseId, positionId) == 0){
			map.put("status", "error");
			map.put("msg", "此公司下无此职位");
			return map;
		}
		
		//设置职位
		List<UserEnterpriseDepartmentPosition> uedpList = userEnterpriseDepartmentPositionRepository.findByUserIdAndEnterpriseId(userId, enterpriseId);
		if(uedpList.size() == 0){
			map.put("status", "error");
			map.put("msg", "此用户不在此公司");
			return map;
		}else{
			
			String positionName = positionRepository.findNameById(positionId);
			String enterpriseName = enterpriseRepository.findNameById(enterpriseId);
			String friendRemarks = contactsRepository.findFriendRemarks(operatorId, userId);
			String enterpriseRemarks = userEnterpriseDepartmentPositionRepository.findEnterpriseRemarks(operatorId, enterpriseId);
			
			String text = "";
			if(friendRemarks != null && friendRemarks.trim().length() != 0){
				text = "您已被管理员【" + friendRemarks + "】任命为" + enterpriseName + "的" + positionName;
			}else{
				text = "您已被管理员【" + enterpriseRemarks + "】任命为" + enterpriseName + "的" + positionName;
			}
			
			Message message = new Message();
			//向公司的员工发送消息,告知管理权限的解除
			message.setUserid(userId);//设置接受者id
			message.setMessage(text);//设置消息内容
			message.setCreatetime(new Date());//设置创建时间
			message.setTitle("系统消息");//设置标题
			message.setMesType(5);//设置消息类型为"系统消息"
			message.setState(2);//设置消息状态为"未处理"
			message.setCreateId(operatorId);//设置创建者id
			message.setSendWay(2);//设置发送方式为"站内信"
			message.setIsRead(0);//设置为"未读"
			messageRepository.save(message);
			
			UserEnterpriseDepartmentPosition uedp = uedpList.get(0);
			uedp.setPositionId(positionId);
			uedp.setUpdateTime(new Date());
			userEnterpriseDepartmentPositionRepository.save(uedp);
			
			map.put("status", "success");
			map.put("msg", "操作成功");
			return map;
		}
	}
	
	/**
	 * 为某个用户设置部门     更新或新增     若为更新,则减少原部门及其父部门及父父部门的人数,再增加新部门及其父部门及父父部门的人数     若为新增,则增加新部门及其父部门及父父部门的人数
	 * @param userId 用户id
	 * @param enterpriseId 公司id
	 * @param departmentId 部门id
	 * @param operatorId 操作者id
	 * @return  status:error/success  msg:错误或成功消息
	 */
	public Map<String, Object> setDepartment(String userId, String enterpriseId, String departmentId, String operatorId){
		Map<String, Object> map = new HashMap<>();
		
		boolean hasEnterprise = enterpriseRepository.exists(enterpriseId);
		if(!hasEnterprise){
			map.put("status", "error");
			map.put("msg", "查无此公司");
			return map;
		}
		
		if(userEnterpriseDepartmentPositionRepository.countByUserIdAndEnterpriseId(userId, enterpriseId) == 0){
			map.put("status", "error");
			map.put("msg", "此用户不在此公司");
			return map;
		}
		
		if(departmentRepository.countByEnterpriseIdAndDepartmentId(enterpriseId, departmentId) == 0){
			map.put("status", "error");
			map.put("msg", "此公司下无此部门");
			return map;
		}
		
		String departmentName = departmentRepository.findNameById(departmentId);
		String enterpriseName = enterpriseRepository.findNameById(enterpriseId);
		String friendRemarks = contactsRepository.findFriendRemarks(operatorId, userId);
		String enterpriseRemarks = userEnterpriseDepartmentPositionRepository.findEnterpriseRemarks(operatorId, enterpriseId);
		
		String text = "";
		if(friendRemarks != null && friendRemarks.trim().length() != 0){
			text = "您已被管理员【" + friendRemarks + "】设置加入" + enterpriseName + "的" + departmentName;
		}else{
			text = "您已被管理员【" + enterpriseRemarks + "】设置加入" + enterpriseName + "的" + departmentName;
		}
		
		Message message = new Message();
		//向公司的员工发送消息,告知管理权限的解除
		message.setUserid(userId);//设置接受者id
		message.setMessage(text);//设置消息内容
		message.setCreatetime(new Date());//设置创建时间
		message.setTitle("系统消息");//设置标题
		message.setMesType(5);//设置消息类型为"系统消息"
		message.setState(2);//设置消息状态为"未处理"
		message.setCreateId(operatorId);//设置创建者id
		message.setSendWay(2);//设置发送方式为"站内信"
		message.setIsRead(0);//设置为"未读"
		messageRepository.save(message);
		
		List<UserEnterpriseDepartmentPosition> uedpList = userEnterpriseDepartmentPositionRepository.findByUserIdAndEnterpriseId(userId, enterpriseId);
		UserEnterpriseDepartmentPosition uedp = null;
		
		//若为更新,则减少原部门及其父部门及父父部门的人数,
		if(uedpList.size() != 0){
			uedp = uedpList.get(0);
			String oldDepartmentId = uedp.getDepartmentId();
			if(oldDepartmentId != null && oldDepartmentId.trim().length() != 0){
				List<String> departmentIdList = departmentService.findAllParentDepartmentId(oldDepartmentId);
				departmentIdList.add(oldDepartmentId);
				departmentDao.minusDepartmentNumber(departmentIdList);
			}
			uedp.setDepartmentId(departmentId);//设置部门id
		}else{
			uedp = new UserEnterpriseDepartmentPosition();
			uedp.setEnterpriseId(enterpriseId);//设置公司id
			uedp.setDepartmentId(departmentId);//设置部门id
			uedp.setUserId(userId);//设置用户id
		}
		
		uedp.setUpdateTime(new Date());
		userEnterpriseDepartmentPositionRepository.save(uedp);
		
		//将该部门及其父部门和父父部门的人数加一
		List<String> departmentIdList = departmentService.findAllParentDepartmentId(departmentId);
		departmentIdList.add(departmentId);
		departmentDao.addDepartmentNumber(departmentIdList);
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		return map;
	}

	/**
	 * 查询某个联系人的详情,从搜索进入
	 * @param username 用户手机号
	 * @param showToUserId 向谁展示的用户id
	 * @return status:error/success msg:错误或成功消息  contactsDetail:联系人详情  isFriend:true/false(是否为好友)
	 */
	public Map<String, Object> findContactsDetailFromSearch(String username, String showToUserId){
		Map<String, Object> map = new HashMap<>();
		
		List<User> userList = userRepository.findByUsername(username);
		if(userList == null || userList.size() == 0){
			map.put("status", "success");
			map.put("msg", "查无此用户");
			map.put("isFriend", false);
			return map;
		}
		
		User user = userList.get(0);
		ContactsDetailVO contactsDetail = new ContactsDetailVO();
		
		//设置好友备注
		contactsDetail.setFriendRemarks(contactsRepository.findFriendRemarks(user.getId(), showToUserId));
		
		//判断是否为自己查询自己
		if(user.getId().equals(showToUserId)){
			contactsDetail.setId(user.getId());
			contactsDetail.setPortrait(user.getPortrait());
			contactsDetail.setNameForShow(user.getNickname()); //展示为昵称
			contactsDetail.setNickname(user.getNickname());
			contactsDetail.setUsername(user.getUsername());
			contactsDetail.setCouldVideo(false);
			
			List<String> enterpriseIdList = userEnterpriseDepartmentPositionDao.findEnterpriseIdByUsersInSameEnterprise(user.getId(), showToUserId);
			List<ContactsDetailVO.CompanyCard> companyCardList = enterpriseDao.findCompanyCardByEnterpriseIdAndUserId(user.getId(), enterpriseIdList);
			//设置所在的部门名称以及职位名称        若部门id为空,则表示该用户无部门
			for(ContactsDetailVO.CompanyCard card : companyCardList){
				if(card.getDepartmentName() == null || card.getDepartmentName().trim().length() == 0){
					card.setDepartmentName("无");
				}else{
					String departmentId = card.getDepartmentName();
					card.setDepartmentName("");
					//若部门不为空,则按一级部门名称_子部门名称_子子部门名称的方式设置所在部门名称
					List<String> allParentDepartmentIdList = departmentService.findAllParentDepartmentId(departmentId);
					allParentDepartmentIdList.add(allParentDepartmentIdList.size(), departmentId);
					
					for(String t : allParentDepartmentIdList){
						card.setDepartmentName(card.getDepartmentName() + "_" + departmentRepository.findNameById(t));
					}
					card.setDepartmentName(card.getDepartmentName().substring("_".length()));
				}
				if(card.getPositionName() == null || card.getPositionName().trim().length() == 0){
					card.setPositionName("无");
				}
			}
			
			//将公司卡片按公司名称排序
			Comparator<ContactsDetailVO.CompanyCard> comparator = new Comparator<ContactsDetailVO.CompanyCard>() {
				@Override
				public int compare(ContactsDetailVO.CompanyCard c1, ContactsDetailVO.CompanyCard c2) {
					String s1 = Pinyin.getStringPinYin(c1.getName());
					String s2 = Pinyin.getStringPinYin(c2.getName());

					return s1.compareTo(s2);
				}
			};
			Collections.sort(companyCardList, comparator);
			contactsDetail.setCompanyCardList(companyCardList);
			
			map.put("status", "success");
			map.put("msg", "操作成功");
			map.put("contactsDetail", contactsDetail);
			map.put("isFriend", false);
			return map;
		}
		
		//判断是否为好友
		List<Contacts> contactsList = contactsRepository.findByUserIdAndShowTOUserId(user.getId(), showToUserId);
		//若不是好友,则展示头像、nameForShow、昵称、手机号、不可发起视频会议
		if(contactsList == null || contactsList.size() == 0){
			contactsDetail.setId(user.getId());
			contactsDetail.setPortrait(user.getPortrait());
			contactsDetail.setNameForShow(user.getNickname()); //非好友关系,展示为昵称
			contactsDetail.setNickname(user.getNickname());
			contactsDetail.setUsername(user.getUsername());
			contactsDetail.setCouldVideo(false);
			
			map.put("status", "success");
			map.put("msg", "操作成功");
			map.put("contactsDetail", contactsDetail);
			map.put("isFriend", false);
			return map;
		}
		
		//若是好友关系,则继续判断是否为同公司
		List<String> enterpriseIdList = userEnterpriseDepartmentPositionDao.findEnterpriseIdByUsersInSameEnterprise(user.getId(), showToUserId);
		//若好友但非同公司,则展示头像、nameForShow、昵称、手机号、可发起视频会议
		if(enterpriseIdList == null || enterpriseIdList.size() == 0){
			contactsDetail.setId(user.getId());
			contactsDetail.setPortrait(user.getPortrait());
			String friendRemarks = contactsList.get(0).getFriendRemarks();//若有好友备注,则展示好友备注,否则展示昵称
			if(friendRemarks != null && friendRemarks.trim().length() != 0){
				contactsDetail.setNameForShow(friendRemarks);
			}else{
				contactsDetail.setNameForShow(user.getNickname());
			}
			contactsDetail.setNickname(user.getNickname());
			contactsDetail.setUsername(user.getUsername());
			contactsDetail.setCouldVideo(true);
			
			map.put("status", "success");
			map.put("msg", "操作成功");
			map.put("contactsDetail", contactsDetail);
			map.put("isFriend", true);
			return map;
		}
		
		//若好友且同公司,则展示头像、nameForShow、昵称、手机号、可发起视频会议、公司卡片(公司名称、企业备注、部门(若非一级部门,则需写上一级部门直到当前部门的所有名称)、职位)
		contactsDetail.setId(user.getId());
		contactsDetail.setPortrait(user.getPortrait());
		String friendRemarks = contactsList.get(0).getFriendRemarks();//若有好友备注,则展示好友备注,否则展示昵称
		if(friendRemarks != null && friendRemarks.trim().length() != 0){
			contactsDetail.setNameForShow(friendRemarks);
		}else{
			contactsDetail.setNameForShow(user.getNickname());
		}
		contactsDetail.setNickname(user.getNickname());
		contactsDetail.setUsername(user.getUsername());
		contactsDetail.setCouldVideo(true);
		
		List<ContactsDetailVO.CompanyCard> companyCardList = enterpriseDao.findCompanyCardByEnterpriseIdAndUserId(user.getId(), enterpriseIdList);
		//设置所在的部门名称以及职位名称        若部门id为空,则表示该用户无部门
		for(ContactsDetailVO.CompanyCard card : companyCardList){
			if(card.getDepartmentName() == null || card.getDepartmentName().trim().length() == 0){
				card.setDepartmentName("无");
			}else{
				String departmentId = card.getDepartmentName();
				card.setDepartmentName("");
				//若部门不为空,则按一级部门名称_子部门名称_子子部门名称的方式设置所在部门名称
				List<String> allParentDepartmentIdList = departmentService.findAllParentDepartmentId(departmentId);
				allParentDepartmentIdList.add(allParentDepartmentIdList.size(), departmentId);
				
				for(String t : allParentDepartmentIdList){
					card.setDepartmentName(card.getDepartmentName() + "_" + departmentRepository.findNameById(t));
				}
				card.setDepartmentName(card.getDepartmentName().substring("_".length()));
			}
			if(card.getPositionName() == null || card.getPositionName().trim().length() == 0){
				card.setPositionName("无");
			}
		}
		
		//将公司卡片按公司名称排序
		Comparator<ContactsDetailVO.CompanyCard> comparator = new Comparator<ContactsDetailVO.CompanyCard>() {
			@Override
			public int compare(ContactsDetailVO.CompanyCard c1, ContactsDetailVO.CompanyCard c2) {
				String s1 = Pinyin.getStringPinYin(c1.getName());
				String s2 = Pinyin.getStringPinYin(c2.getName());

				return s1.compareTo(s2);
			}
		};
		Collections.sort(companyCardList, comparator);
		contactsDetail.setCompanyCardList(companyCardList);
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		map.put("contactsDetail", contactsDetail);
		map.put("isFriend", true);
		return map;
	}
	
	/**
	 * 查询某个联系人的详情,从好友列表进入
	 * @param username 用户手机号
	 * @param showToUserId 向谁展示的用户id 
	 * @return status:error/success msg:错误或成功消息  contactsDetail:联系人详情   isFriend:true/false(是否为好友)
	 */
	public Map<String, Object> findContactsDetailFromContactsList(String username, String showToUserId){
		Map<String, Object> map = new HashMap<>();
		
		List<User> userList = userRepository.findByUsername(username);
		if(userList == null || userList.size() == 0){
			map.put("status", "error");
			map.put("msg", "查无此用户");
			return map;
		}
		
		User user = userList.get(0);
		ContactsDetailVO contactsDetail = new ContactsDetailVO();
		//判断是否为好友
		List<Contacts> contactsList = contactsRepository.findByUserIdAndShowTOUserId(user.getId(), showToUserId);
		if(contactsList == null || contactsList.size() == 0){
			map.put("status", "error");
			map.put("msg", "该用户与您不是好友关系");
			return map;
		}
		
		//设置好友备注
		contactsDetail.setFriendRemarks(contactsRepository.findFriendRemarks(user.getId(), showToUserId));
		
		//设置头像、nameForShow、昵称、手机号、可发起视频会议
		contactsDetail.setId(user.getId());
		contactsDetail.setPortrait(user.getPortrait());
		String friendRemarks = contactsList.get(0).getFriendRemarks();//若有好友备注,则展示好友备注,否则展示昵称
		if(friendRemarks != null && friendRemarks.trim().length() != 0){
			contactsDetail.setNameForShow(friendRemarks);
		}else{
			contactsDetail.setNameForShow(user.getNickname());
		}
		contactsDetail.setNickname(user.getNickname());
		contactsDetail.setUsername(user.getUsername());
		contactsDetail.setCouldVideo(true);
		
		//设置公司卡片
		List<String> enterpriseIdList = userEnterpriseDepartmentPositionDao.findEnterpriseIdByUsersInSameEnterprise(user.getId(), showToUserId);
		
		if(enterpriseIdList == null || enterpriseIdList.size() == 0){
			map.put("status", "success");
			map.put("msg", "操作成功");
			map.put("contactsDetail", contactsDetail);
			map.put("isFriend", true);
			return map;
		}
		List<ContactsDetailVO.CompanyCard> companyCardList = enterpriseDao.findCompanyCardByEnterpriseIdAndUserId(user.getId(), enterpriseIdList);
		//设置所在的部门名称        若部门id为空,则表示该用户无部门
		for(ContactsDetailVO.CompanyCard card : companyCardList){
			if(card.getDepartmentName() == null || card.getDepartmentName().trim().length() == 0){
				card.setDepartmentName("无");
			}else{
				String departmentId = card.getDepartmentName();
				card.setDepartmentName("");
				//若部门不为空,则按一级部门名称_子部门名称_子子部门名称的方式设置所在部门名称
				List<String> allParentDepartmentIdList = departmentService.findAllParentDepartmentId(departmentId);
				allParentDepartmentIdList.add(allParentDepartmentIdList.size(), departmentId);
				
				for(String t : allParentDepartmentIdList){
					card.setDepartmentName(card.getDepartmentName() + "_" + departmentRepository.findNameById(t));
				}
				card.setDepartmentName(card.getDepartmentName().substring("_".length()));
			}
			if(card.getPositionName() == null || card.getPositionName().trim().length() == 0){
				card.setPositionName("无");
			}
		}
		
		//将公司卡片按公司名称排序
		Comparator<ContactsDetailVO.CompanyCard> comparator = new Comparator<ContactsDetailVO.CompanyCard>() {
			@Override
			public int compare(ContactsDetailVO.CompanyCard c1, ContactsDetailVO.CompanyCard c2) {
				String s1 = Pinyin.getStringPinYin(c1.getName());
				String s2 = Pinyin.getStringPinYin(c2.getName());

				return s1.compareTo(s2);
			}
		};
		Collections.sort(companyCardList, comparator);
		contactsDetail.setCompanyCardList(companyCardList);
		
		map.put("status", "success");
		map.put("msg", "操作成功");
		map.put("contactsDetail", contactsDetail);
		map.put("isFriend", true);
		
		return map;
	}
	

	/**
	 * 查询某个用户在某个公司下的详情
	 * @param enterpriseId 公司id
	 * @param username 用户手机号
	 * @param showToUserId 向谁展示的用户id
	 * @return status:error/success  msg:错误或成功消息
	 *         userDetail:userDetailVO对象
	 *		   permissionList:操作者权限集合
	 *		   isFriend:是否为好友关系
	 */
	@Override
	public Map<String, Object> findUserDetailVO(String enterpriseId, String username, String showToUserId) {
		List<User> userList= userRepository.findByUsername(username);
		if(userList == null || userList.size() == 0){
			return MapAsReturn.setStatusError("查无此用户");
		}
	
		if(userEnterpriseDepartmentPositionRepository.countByUserIdAndEnterpriseId(showToUserId, enterpriseId) == 0){
			return MapAsReturn.setStatusError("您不在所操作的公司内");
		}
	
		User user = userList.get(0);
		if(userEnterpriseDepartmentPositionRepository.countByUserIdAndEnterpriseId(user.getId(), enterpriseId) == 0){
			return MapAsReturn.setStatusError("查询用户不在所操作公司内");
		}
		
		UserDetailVO userDetailVOTemp = userDao.findUserDetailVO(enterpriseId, user.getId(), showToUserId);
		UserDetailVO userDetailVO = new UserDetailVO();
		userDetailVO.setId(userDetailVOTemp.getId());
		userDetailVO.setPortrait(userDetailVOTemp.getPortrait());
		userDetailVO.setNameForShow(userDetailVOTemp.getNameForShow());
		userDetailVO.setFriendRemarks(contactsRepository.findFriendRemarks(user.getId(), showToUserId));
		userDetailVO.setNickname(userDetailVOTemp.getNickname());
		userDetailVO.setUsername(userDetailVOTemp.getUsername());
		userDetailVO.setEnterpriseName(userDetailVOTemp.getEnterpriseName());
		userDetailVO.setEnterpriseRemarks(userDetailVOTemp.getEnterpriseRemarks());
		userDetailVO.setDepartmentName(userDetailVOTemp.getDepartmentName());
		userDetailVO.setPositionName(userDetailVOTemp.getPositionName());
		userDetailVO.setCouldVideo(true);
		
		//设置被查询用户在该公司的角色
		UserEnterprisePermissionGroup uepg = userEnterprisePermissionGroupRepository.findByUserIdAndEnterpriseId(user.getId(), enterpriseId);
		userDetailVO.setRoleId("3");
		if(uepg != null && !StringUtils.isBlank(uepg.getPermissionGroupsDescription())){
			if(uepg.getOpenDescription().contains("SUPER_PERMISSION")){
				userDetailVO.setRoleId("1");
			}else{
				userDetailVO.setRoleId("2");
			}
		}
		
		//设置管理范围
		List<Permission> permissionList = new ArrayList<>();
		//若为超级管理员,则拥有所有权限
		if(uepg != null){
			permissionList = uepg.getOpenPermission();
		}
		userDetailVO.setManageRange(permissionList);
		
		//设置部门名称(若部门id为空,则显示'无')
		String departmentId = userDetailVO.getDepartmentName();
		userDetailVO.setDepartmentName("");
		if(departmentId == null || departmentId.trim().length() == 0){
			userDetailVO.setDepartmentName("无");
		}else{
			//若部门不为空,则按一级部门名称_子部门名称_子子部门名称的方式设置所在部门名称
			List<String> allParentDepartmentIdList = departmentService.findAllParentDepartmentId(departmentId);
			allParentDepartmentIdList.add(allParentDepartmentIdList.size(), departmentId);
			
			for(String t : allParentDepartmentIdList){
				userDetailVO.setDepartmentName(userDetailVO.getDepartmentName() + "_" + departmentRepository.findNameById(t));
			}
			userDetailVO.setDepartmentName(userDetailVO.getDepartmentName().substring("_".length()));
		}
		
		//设置职位名称
		String positionId = userDetailVO.getPositionName();
		if(positionId == null || positionId.trim().length() == 0){
			userDetailVO.setPositionName("无");
		}else{
			userDetailVO.setPositionName(positionRepository.findNameById(positionId));
		}
		
		//获取操作者权限
		UserEnterprisePermissionGroup uepg1 = userEnterprisePermissionGroupRepository.findByUserIdAndEnterpriseId(showToUserId, enterpriseId);
		List<Permission> permissionList1 = null;
		if(null == uepg1){
			permissionList1 = new ArrayList<Permission>();
		}else{
			permissionList1 = uepg1.getOpenPermission();
			if(!uepg1.getOpenDescription().contains("SUPER_PERMISSION") && uepg1.getOpenDescription().contains("DELETE_EMPLOYEE") && uepg.getOpenDescription().contains("DELETE_EMPLOYEE")){
				for(Permission element : permissionList1){
					if(element.getDescription().contains("DELETE_EMPLOYEE")){
						permissionList1.remove(element);
						break;
					}
				}
			}
		}
		
		//当自己查看自己或操作者拥有超级管理员权限时,显示被查看者的管理范围
		if(!user.getId().equals(showToUserId) && (uepg1 == null || !uepg1.getOpenDescription().contains("SUPER_PERMISSION"))){
			userDetailVO.setManageRange(new ArrayList<>());
		}
		
		Map<String, Object> map = MapAsReturn.setStatusSuccess("userDetail", userDetailVO);
		map.put("permissionList", permissionList1);
		
		//判断是否为好友关系
		if(contactsRepository.countByUserIdAndUserId(user.getId(), showToUserId) > 0){
			map.put("isFriend", true);
		}else{
			map.put("isFriend", false);
		}
		
		return map;
	}
	
	/**
	 * 查询某人在某公司下的关于公司管理的管理范围
	 * @param enterpriseId 公司id
	 * @param userId 用户id
	 * @return status:error/success msg:错误或成功消息   permissionList:基本权限集合
	 */
	public Map<String, Object> findManageRangeAboutEnterpriseManage(String enterpriseId, String userId){
		UserEnterprisePermissionGroup uepg = userEnterprisePermissionGroupRepository.findByUserIdAndEnterpriseId(userId, enterpriseId);
		
		List<Permission> permissionList = new ArrayList<>();
		if(null == uepg){
			return MapAsReturn.setStatusSuccess("permissionList", permissionList);
		}
		
		if(uepg.getOpenDescription().contains("SUPER_PERMISSION")){
			permissionList.add(permissionRepository.findByDescription("SUPER_PERMISSION"));
			permissionList.addAll(permissionRepository.findByType(2));
			return MapAsReturn.setStatusSuccess("permissionList", permissionList);
		}
		
		for(Permission element : uepg.getOpenPermission()){
			if(element.getType() != 1){
				permissionList.add(element);
			}
		}
		
		return MapAsReturn.setStatusSuccess("permissionList", permissionList);
	}
	
	public void payedDeposit(String userId,String oid,String channel,Integer amount){
		User user = userRepository.findOne(userId);
		user.setIsPledge(1);
		userRepository.save(user);
		DepositRecord depositRecord = new DepositRecord();
		depositRecord.setOid(oid);
		depositRecord.setAmount(amount);
		depositRecord.setChannel(channel);
		depositRecord.setUid(userId);
		depositRecord.setType("0");
		depositRecordRepository.save(depositRecord);
	}
	
	public List<DepositRecord> findAllByUser(String userId) {
		return depositRecordRepository.findByUidOrderByCreateTimeDesc(userId);
	}
}